﻿using System.Windows;
using System.Windows.Controls;

namespace DataModel
{
    /// <summary>
    /// The purpose of the binding helper is to support changeing when the databinding's are updated to when the property changes.
    /// Currently supports only TextBoxes and PasswordBoxes but could be extended.
    /// </summary>
    public static class BindingHelper
    {
        public static readonly DependencyProperty UpdateSourceOnChangeProperty =
            DependencyProperty.RegisterAttached(
            "UpdateSourceOnChange",
            typeof(bool),
            typeof(BindingHelper),
            new PropertyMetadata(false, OnPropertyChanged));
        public static bool GetUpdateSourceOnChange(DependencyObject obj)
        {
            return (bool)obj.GetValue(UpdateSourceOnChangeProperty);
        }
        public static void SetUpdateSourceOnChange(DependencyObject obj, bool value)
        {
            obj.SetValue(UpdateSourceOnChangeProperty, value);
        }
        private static void OnPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            bool value = (bool)e.NewValue;
            if (obj is TextBox)
            {
                OnTextBoxValueChanged((TextBox)obj, value);
            }
            if (obj is PasswordBox)
            {
                OnPasswordValueChanged((PasswordBox)obj, value);
            }
        }
        static void OnTextBoxValueChanged(TextBox txt, bool value)
        {
            if (value)
                txt.TextChanged += OnTextChanged;
            else
                txt.TextChanged -= OnTextChanged;
        }
        static void OnTextChanged(object sender, TextChangedEventArgs e)
        {
            var txt = sender as TextBox;
            if (txt == null)
                return;
            var be = txt.GetBindingExpression(TextBox.TextProperty);
            if (be != null)
            {
                be.UpdateSource();
            }
        }
        static void OnPasswordValueChanged(PasswordBox pwd, bool value)
        {
            if (value)
                pwd.PasswordChanged += OnPasswordChanged;
            else
                pwd.PasswordChanged -= OnPasswordChanged;
        }

        static void OnPasswordChanged(object sender, RoutedEventArgs e)
        {
            var pwd = sender as PasswordBox;
            if (pwd == null)
                return;
            var be = pwd.GetBindingExpression(PasswordBox.PasswordProperty);
            if (be != null)
            {
                be.UpdateSource();
            }
        }
    }
}
